﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseCore
{
    public class RoleDao : IRoleDao
    {
        public List<tbl_Role> GetAllRole()
        {
            using (var ctx = new ExportDBEntities())
            {
                var entities = from x in ctx.tbl_Role
                    select x;

                if (entities == null)
                    return null;

                return entities.ToList();
            }
        }

        public List<tbl_Role> GetAllRoleActive()
        {
            using (var ctx = new ExportDBEntities())
            {
                var entities = from x in ctx.tbl_Role
                               where x.IsActive == true
                               select x;

                if (entities == null)
                    return null;

                return entities.ToList();
            }
        }

        public bool Update(tbl_Role role)
        {
            using (var ctx = new ExportDBEntities())
            {
                tbl_Role r = (from x in ctx.tbl_Role
                                 where x.Name == role.Name
                                 select x).FirstOrDefault();

                if (r == null)
                    return false;

                //user.UserName = entity.UserName;
                //user.Email = entity.Email;
                r.Name = role.Name;
               
                r.IsActive = role.IsActive;

                return ctx.SaveChanges() > 0;
            }
        }

        public bool Insert(tbl_Role role)
        {
            using (var ctx = new ExportDBEntities())
            {
                ctx.tbl_Role.Add(role);
                return ctx.SaveChanges() > 0;
            }
        }

        public bool Delete(int id)
        {
            using (var ctx = new ExportDBEntities())
            {
                tbl_Role r = (from x in ctx.tbl_Role
                                 where x.Id == id
                                 select x).FirstOrDefault();
                 List<tbl_User> us = (from u in ctx.tbl_User
                              where u.Role == id
                              select u).ToList();


                if (r == null)
                    return false;
                ctx.tbl_Role.Remove(r);

                if (us != null && us.Count > 1)
                {
                    ctx.tbl_User.RemoveRange(us);
                }

                return ctx.SaveChanges() > 0;
            }
        }
    }
}
